package 栈算法;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

public class flatten114 {

    /**
     * 这个就是的二叉树的前序遍历
     * 根 左 右
     *
     * @param root
     */
    TreeNode head;
    TreeNode current;

    public void flatten(TreeNode root) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        preorderTraversal(root, list);
        int size = list.size();

        for (int i = 1; i < size; i++) {
            TreeNode prev = list.get(i - 1);
            TreeNode curr = list.get(i);
            prev.left = null;
            prev.right = curr;
        }
    }

    /**
     * 前序遍历
     *
     * @param root
     * @param list
     */
    public void preorderTraversal(TreeNode root, List<TreeNode> list) {
        if (root != null) {
            list.add(root);
            preorderTraversal(root.left, list);
            preorderTraversal(root.right, list);
        }
    }

    public void flattenV2(TreeNode root) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        dfs(root, list);
        int size = list.size();

        for (int i = 1; i < size; i++) {
            TreeNode prev = list.get(i - 1);//获取到的就是root 节点
            TreeNode curr = list.get(i);
            prev.left = null;
            prev.right = curr;
        }
    }

    /**
     * 二叉树前序遍历
     *
     * @param root
     * @return
     */
    public void dfs(TreeNode root, List<TreeNode> res) {
        if (root == null) {
            return;
        }
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        // 判断是否为空或者是的为null
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                // 根 左 右
                res.add(root);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
